<style lang="less" rel="stylesheet/less" type="text/less">
.api-views {
  padding-top: 20px;
  width: 100%;
  padding-left: 20px;
  min-width: 1140px;
  height: 100%;
}
.look-views {
  margin-top: 20px;
}
.row-page {
  margin-top: 20px;
  padding-bottom: 20px;
}
.ivu-modal-body {
  font-size: 16px;
  .ivu-form-item-label {
    font-size: 16px;
  }
}
.ivu-table .user-locked td {
  background-color: orange;
  color: #fff;
}

.ivu-table .admin-locked td {
  background-color: red;
  color: #fff;
}
.ivu-table .unactive td {
  background-color: #ffd77a;
  color: #fff;
}
.ivu-table .normal td {
  background-color: #187;
  color: #fff;
}
</style>

<template>
  <div v-if="!is_showLook" class="api-views">
    <Button v-if="!is_showCreate" type="primary" size="large" @click="toCreate">+创建API key</Button>
    <Button v-else type="primary" size="large" @click="toIndex">查看API KEY</Button>
    <Table
      v-if="!is_showCreate"
      :columns="titleName"
      :data="data"
      :loading="table_loading"
      :row-class-name="apikeyColor"
      class="look-views"
    />
	<br/>

    <!-- 分页组件 -->
    <Row v-if="!is_showCreate" type="flex" class="row-page" justify="center">
      <Page
        :total="apiTotal"
        :current="apipage_info.page"
        :page-size="apipage_info.per_page"
        :page-size-opts="[10,30,50]"
	
        placement="top"
        show-sizer
        show-total
        @on-change="apipageChange"
        @on-page-size-change="apiperPageChange"
      />
    </Row>

    <API-KEY v-if="is_showCreate" />
    <Modal v-model="show_modal" title="APIKEY详情&&状态修改" @on-cancel="hide_Modal">
      <EDIT v-if="show_modal" :apikeys_detail="apikeys_detail" @update="edit_ok" />

      <div slot="footer" />
    </Modal>

    <!-- 权限弹框 -->
    <Modal v-model="show_permission" title="权限详情" @on-cancel="hide_permission" width="650">
      <Permission
        v-if="show_permission"
        :permission_detail="permission_detail"
        :data="dataList"
        @toAPIBOOKDetail="toAPIBOOKDetail"
      />

      <div slot="footer" />
    </Modal>
  </div>
  <div v-else class="api-views">
    <Button type="primary" size="large" @click="toIndex">查看API KEY</Button>
    <LOOK :logs-list="logsList" class="look-views" :look_loading="look_loading" />
    <!-- 分页组件 -->
    <Row type="flex" class="row-page" justify="center">
      <Page
        :total="logsTotal"
        :current="page_info.page"
        :page-size="page_info.per_page"
        :page-size-opts="[10,30,50]"
        placement="top"
        show-sizer
        show-total
        @on-change="pageChange"
        @on-page-size-change="perPageChange"
      />
    </Row>
  </div>
</template>
<script>
import qs from 'qs';
import APIKEY from './API-KEY.vue';
import LOOK from './look.vue';
import EDIT from './edit.vue';
import Permission from './permission.vue'

export default {
    	components: {
		'API-KEY': APIKEY,
		LOOK,
		EDIT,
		Permission
	},
	data() {
		return {
			table_loading: false,
			look_loading:false,
			logsList: [],
			dataList:[],
			show_permission:false,
			apikeys_detail: {},
			permission_detail:{},
			apiTotal: null,
			logsTotal: null,
			is_showCreate: false,
			is_showLook: false,
			// logsPages: null,
			token: '',
			requestId: null,
			show_modal: false,
			page_info: {
				// 分页信息
				page: 1,
				per_page: 10,

			},
			search_info: {

				page: 1,
				per_page: 10,
			},

			apipage_info: {
				// 分页信息
				page: 1,
				per_page: 10,

			},
			apisearch_info: {

				page: 1,
				per_page: 10,
			},

			titleName: [
				{
					title: '应用名称',
					key: 'name',
					width: '120px',

				},
				{
					title: 'API Key',
					key: 'key',

				},
				{
					title: 'API Secret',
					key: 'secret',
					width: '150px',

				},
				{
					title: '状态',
					width: '80px',
					render: (h, { row }) => {
						let realStatus;
						if (row.status === 'normal') {
							realStatus = (<div>正常</div>);
						} else if (row.status === 'user-locked') {
							realStatus = (<div>锁定</div>);
						} else if (row.status === 'admin-locked') {
							realStatus = (<div>冻结</div>);
						} else if (row.status === 'unactive') {
							realStatus = (<div>未激活</div>);
						} else if (row.status === 'outdated') {
							realStatus = (<div>过期</div>);
						}
						return realStatus;
					},
				},
				{
					title: '计费方式',
					render: (h, { row }) => {
						let type = <div>测试</div>;
						if (row.type === 1) {
							type = (<div>按次计费</div>);
						}
						if (row.type === 2) {
							this.$moment.locale(navigator.language);
							let real_startTime = this.$moment
              .utc(`${row.start_time}`)
              .local()
			  .format("lll");      
						   
						   						
							let real_endTime = this.$moment
              .utc(`${row.end_time}`)
              .local()
			  .format("lll");   

							type = (
								<div>
									<div>按时间段计费:</div>
									<div>{real_startTime}------{real_endTime}</div>
								</div>
							);
						}
						if (row.type === 3) {
							type = (<div>永久授权</div>);
						}
						return type;
					},
				},
				{
					title: '操作',
					width: '620px',
					// 根据状态相应渲染
					render: (h, { row }) => {
						let status = '';
						let operating = (
							<div>  
								<Button name="index__per" size="small" onClick={() => { this.permission(row); }} type="primary"
									style="width:145px"
								>权限</Button>
								<Button name="index__edit" size="small" onClick={() => { this.editAPI(row); }} type="primary"
									style="width:145px;margin-left: 8px"
								>编辑</Button>
								<Button name="index__look" size="small"style="margin-left: 8px" onClick={() => { this.lookAPI(row.id); }} type="primary">查看apikey调用记录</Button>
								<Button name="index__delete" size="small" style="margin-left: 8px;width:145px" onClick={() => { this.deleteAPI(row.id); }} type="error">删除</Button>
							</div>);
						if (!row.type) {
							operating = (
								<div>
									<Button name="index__per" size="small" onClick={() => { this.permission(row); }} type="primary"
									style="width:145px"
								    >权限</Button>
									<Button name="index__edit" size="small" onClick={() => { this.editAPI(row); }} type="primary"
										style="width:145px;margin-left: 8px"
									>编辑</Button>
									<Button name="index__look" size="small"style="margin-left: 8px" onClick={() => { this.lookAPI(row.id); }} type="primary">查看apikey调用记录</Button>
									<Button name="index__delete" size="small" disabled style="margin-left: 8px;width:145px" onClick={() => { this.deleteAPI(row.id); }} type="error">测试api无法删除</Button>
								</div>);
						}
						if (row.status === 'admin-locked') {
							status = '应用被服务商冻结';
						} else if (row.status === 'unactive') {
							status = '等待服务商激活';
						} else if (row.status === 'outdated') {
							status = '请联系服务商延期';
						}

						{ if (row.status === 'admin-locked' || row.status === 'unactive' || row.status === 'outdated') {

							operating = (
								<div>  
									<Button name="index__per" size="small" onClick={() => { this.permission(row); }} type="primary"
									style="width:145px"
								    >权限</Button>
									<Button name="index__edit" size="small" onClick={() => { this.editAPI(row); }} disabled type="primary"
										style="width:145px;margin-left: 8px"
									>{status}</Button>
									<Button name="index__look" size="small"style="margin-left: 8px" onClick={() => { this.lookAPI(row.id); }} type="primary">查看apikey调用记录</Button>
									<Button name="index__delete" size="small" style="margin-left: 8px;width:145px" onClick={() => { this.deleteAPI(row.id); }} type="error">删除</Button>
								</div>);
							if (!row.type) {
								operating = (
									<div>
										<Button name="index__per" size="small" onClick={() => { this.permission(row); }} type="primary"
									style="width:145px"
								    >权限</Button>
										<Button name="index__edit" size="small" onClick={() => { this.editAPI(row); }} disabled type="primary"
											style="width:145px;margin-left: 8px"
										>{status}</Button>
										<Button name="index__look" size="small"style="margin-left: 8px" onClick={() => { this.lookAPI(row.id); }} type="primary">查看apikey调用记录</Button>
										<Button name="index__delete" disabled size="small" style="margin-left: 8px;width:145px" onClick={() => { this.deleteAPI(row.id); }} type="error">测试api无法删除</Button>
									</div>);
							}

						} }
						return operating;

					},
				},
			],
			data: [],
		};
	},
	created() {
		this.token = sessionStorage.getItem('token');

		this.APILIST(this.apipage_info);
	},
	methods: {
		/**
        * 根据apikey状态改变颜色
        *
        */
		apikeyColor(row, index) {
			if (row.status === 'user-locked') {
				return 'user-locked';
			} else if (row.status === 'admin-locked' || row.status === 'outdated') {
				return 'admin-locked';
			} else if (row.status === 'unactive') {
				return 'unactive';
			}
			return 'normal';

		},
		/**
       * 页码改变
       * @param  {string} page {当前页码}
       * @return {undefined}
       */
		pageChange(page) {
			this.search_info.page = page;
			this.search_info.per_page = this.page_info.per_page;
			this.pageAPI(this.search_info);
		},

		/**
       * 每页显示数改变
       * @param  {string} size {当前每页显示数}
       * @return {undefined}
       */
		perPageChange(size) {
			this.search_info.per_page = size;
			this.page_info.per_page = size;
			this.pageAPI(this.page_info);
		},

		/**
       * api页码改变
       * @param  {string} page {当前页码}
       * @return {undefined}
       */
		apipageChange(page) {
			this.apisearch_info.page = page;
			this.apisearch_info.per_page = this.apipage_info.per_page;
			this.APILIST(this.apisearch_info);
		},

		/**
       * api每页显示数改变
       * @param  {string} size {当前每页显示数}
       * @return {undefined}
       */
		apiperPageChange(size) {
			this.apisearch_info.per_page = size;
			this.apipage_info.per_page = size;
			this.APILIST(this.apipage_info);
		},

		hide_Modal() {
			this.apikeys_detail = null;
		},

		hide_permission(){
			 this.permission_detail = null;
			 this.dataList=[]
		},


		// 删除单条api-key
		deleteAPI(id) {
			this.$Modal.confirm({

				title: '温馨提示', // '温馨提示',
				content: '删除之后将无法恢复，确定吗?', // '删除之后将无法恢复，确定吗？',
				onOk: () => {
					 
					const deleteData = {
						apikey_id: id,
						token: this.token,
						_method: 'DELETE',
					};
					this.table_loading=true
					this.axios.post(`${window.location.origin}/admin/api/v1/apikey/delete`, qs.stringify(deleteData))
						.then(({ data }) => {
							if (data.code === 200) {
								
								this.APILIST(this.apisearch_info);
								this.$Message.success('删除成功');
							} else if (data.code === 7003) {
								this.$Message.error({
									content: 'token验证失败,过期或token错误,请重新登录',
									duration: 5,
									closable: true,

								});
								this.$router.push({
									path: '/login',
								});
							} else {
								throw new Error(data.error);
							}
						})
		            .catch((err) => {
						 this.table_loading=false
							this.$Message.error({
								content: err.message || err.statusText,
								duration: 5,
								closable: true,
							});
						});
					
            		},
				onCancel: () => {},

			});
		},
		// api-key列表
		APILIST(param) {
		
			param.token = this.token;
			const query_str = qs.stringify(param);
			this.table_loading=true;
			this.axios.post(`${window.location.origin}/admin/api/v1/apikeys`, query_str)
				.then(({ data }) => {
					if (data.code === 200) {
						this.data = data.apikeys.data;
						this.apiTotal = data.apikeys.total;
					} else if (data.code === 7003) {
						this.$Message.error({
							content: 'token验证失败,过期或token错误,请重新登录',
							duration: 5,
							closable: true,

						});
						this.$router.push({
							path: '/login',
						});
					} else {
						throw new Error(data.error);
					}
				})
		            .catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});
				})
				.then(()=>{
					this.table_loading=false
				})
			
		},
		toCreate() {
			this.is_showCreate = true;
		},
		toIndex() {
			this.is_showCreate = false;
			this.is_showLook = false;
			this.APILIST(this.apipage_info);
		},

		// id请求日志
		lookAPI(id) {
			

			this.requestId = id;

			const lookData = {
				token: this.token,
				apikey_id: this.requestId,
				page: this.page_info.page,
				per_page: this.page_info.per_page,
			};
		   this.is_showLook = true;
		   this.look_loading=true
			this.axios.post(`${window.location.origin}/admin/api/v1/apikey/logs`, qs.stringify(lookData))
				.then(({ data }) => {
					if (data.code === 200) {
						this.logsList = data.logs.data;
						this.logsTotal = data.logs.total;
						// this.logsPages = data.pages.data;
		         	
					} else if (data.code === 7003) {
						this.$Message.error({
							content: 'token验证失败,过期或token错误,请重新登录',
							duration: 5,
							closable: true,

						});
						this.$router.push({
							path: '/login',
						});
					} else {
						throw new Error(data.error);
					}
				})
				.catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});
				})
				.then(()=>{
					this.look_loading=false
				})
			
		},


		// 分页请求日志
		pageAPI(param) {
			
			const lookData = {
				token: this.token,
				apikey_id: this.requestId,
				page: param.page,
				per_page: param.per_page,
			};
			
			this.look_loading=true
			this.axios.post(`${window.location.origin}/admin/api/v1/apikey/logs`, qs.stringify(lookData))
				.then(({ data }) => {
					if (data.code === 200) {
						this.logsList = data.logs.data;
						// this.logsPages = data.data.pages;
		         	// this.is_showLook = true;
					} else if (data.code === 7003) {
						this.$Message.error({
							content: 'token验证失败,过期或token错误,请重新登录',
							duration: 5,
							closable: true,

						});
						this.$router.push({
							path: '/login',
						});
					} else {
						throw new Error(data.error);
					}
				})
				.catch((err) => {
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});
				})
				.then(()=>{
					this.look_loading=false
				})
		
		},

	   // 请求点击编辑时的详细内容
		editAPI(detail) {
		  this.apikeys_detail = detail;
	       this.show_modal = true;
		},

		/**
		 * 权限按钮弹框
		 */
        permission(detail){
		   this.permission_detail=detail

		   this.APIPERMISSIONLIST(detail.id); //请求api文档列表

		},

		// 修改成功回调
		edit_ok(param) {
		
			param.token=this.token
			this.show_modal = false;
			this.table_loading=true
			this.axios.post(`${window.location.origin}/admin/api/v1/apikey/status/update`, qs.stringify(param))
				.then(({ data }) => {
					if (data.code === 200) {
						
						
						this.APILIST(this.apisearch_info);
						this.$Message.success('更新成功');
					} else if (data.code === 7003) {
						this.$Message.error({
							content: 'token验证失败,过期或token错误,请重新登录',
							duration: 5,
							closable: true,

						});
						this.$router.push({
							path: '/login',
						});
					} else {
						throw new Error(data.error);
					}
				})
				.catch((err) => {
				 this.table_loading=false
					this.$Message.error({
						content: err.message || err.statusText,
						duration: 5,
						closable: true,
					});
				});
		
		},

		/*
		api文档列表请求
		*/
		APIPERMISSIONLIST(id) {
		this.table_loading=true
      this.axios
        .get(`${window.location.origin}/admin/api/v1/docs?group=face`)
        .then(({ data }) => {
          if (data.code === 200) {
			this.PermissionList(id);   //权限列表请求
            this.dataList = data.apiDocs;
          } else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        });
	},
	PermissionList(id){
       this.axios
        .get(`${window.location.origin}/admin/api/v1/apikey/apigateway`,{
			params:{
				token:this.token,
				apikey_id:id,
				group:"face"
			}
		})
        .then(({ data }) => {
          if (data.code === 200) {
			  if (this.permission_detail.type==0) {
			     for (let bout = 0; bout < this.dataList.length; bout++) {
					this.dataList[bout].price="免费"
					 
				 }
			  }else if(data.gateways.length>0) {
				 for (let index = 0; index < data.gateways.length; index++) {
					 for (let count =0;count < this.dataList.length;count++) {
					 if(this.dataList[count].name===data.gateways[index].endpoint){
						this.dataList[count].price="免费"
						

					}
						 
					 }
				
					 
				 }
			 }
		this.table_loading=false
		this.show_permission=true;
          } else if (data.code === 7003) {
				this.$Message.error({
							content: 'token验证失败,过期或token错误,请重新登录',
							duration: 5,
							closable: true,

						});
						this.$router.push({
							path: '/login',
						});
			} else {
            throw new Error(data.error);
          }
        })
        .catch(err => {
          this.$Message.error({
            content: err.message || err.statusText,
            duration: 5,
            closable: true
          });
        });
	},
	
	// 跳转到api文档
	toAPIBOOKDetail(name){
		this.show_permission=false

		/*
		若直接跳转会导致modal还没来得及关闭，会导致api文档无法正常滚动
		故设置一个小定时器
		*/
		setTimeout(() => {
				this.$router.push({
				path: `/api/${name}`,
				params: {
					name,
				},
			});
		}, 100);
    
	
	},
	},
};
</script>
